//
//  SecarSybolViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/12/18.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "SecarSybolViewController.h"
#import "AJSearchBar.h"
#import "SearchViewModel.h"
#import "SearchCell.h"
#import "Y_StockChartViewController.h"
#import "CheckVersionAlearView.h"
@interface SecarSybolViewController ()<SearchDelegate,UITableViewDelegate,UITableViewDataSource>
/*! 搜索框 */
@property(nonatomic,strong)AJSearchBar *searchBar;
@property(nonatomic,strong)UIView *searchbgView;
/*! SearchViewModel */
@property(nonatomic,strong)SearchViewModel *searchVM;
@property(nonatomic,strong)NSMutableArray * searchDataArray;
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong) NoNetworkView * workView;
@property (nonatomic,assign) BOOL  isSearch;
@end

@implementation SecarSybolViewController
- (void)viewWillDisappear:(BOOL)animated
{
    _searchbgView.hidden = YES;
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}
- (void)viewWillAppear:(BOOL)animated
{
    _searchbgView.hidden = NO;
}
- (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setShadowImage:[self imageWithColor:CELLCOLOR]];
    _isSearch = NO;
     _searchVM = [[SearchViewModel alloc]init];
    NSArray * historys = [_searchVM readHistory];
    NSArray * dataArray = [NSArray bg_arrayWithName:FMDBName_Symbol];
    for (NSString *str in historys) {
        
        for (HomeModle * modle in dataArray) {
            
            if ([modle.name isEqualToString:str]) {
                
                [self.searchDataArray addObject:modle];
            }
        }
    }
    [self placeholderViewWithFrame:self.tableView.frame title:Localized(@"search_no_Historysymbol")];
    self.view.backgroundColor = TABLEVIEWLCOLOR;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:self.searchbgView];
    self.navigationItem.leftBarButtonItem = item;
    [_searchbgView addSubview:self.searchBar];
    [self.view addSubview:self.tableView];
    
    
}
#pragma mark---懒加载
- (UIView *)searchbgView
{
    if (!_searchbgView) {
        _searchbgView = [[UIView alloc]initWithFrame:CGRectMake(-20, 16, UIScreenWidth, kStatusBarAndNavigationBarHeight)];
        _searchbgView.backgroundColor = TABLEVIEWLCOLOR;
        
    }
    return _searchbgView;
}
- (AJSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[AJSearchBar alloc]initWithFrame:CGRectMake(0, 0, _searchbgView.width -30, 40)];
        _searchBar.SearchDelegate = self;
    }
    return _searchBar;
}
- (NSMutableArray *)searchDataArray
{
    if (!_searchDataArray) {
        _searchDataArray = [[NSMutableArray alloc] init];
    }
    return _searchDataArray;
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight  -kStatusBarAndNavigationBarHeight -IPhoneTop)];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[SearchCell class] forCellReuseIdentifier:@"SearchCell"];
    }
    return _tableView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RealValue_H(100);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isSearch ||self.searchDataArray.count ==0) {
         return self.searchDataArray.count;
    }else
    {
         return self.searchDataArray.count +1;
    }
   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
    if (_isSearch) {
          cell.symbolLable.textColor = MAINTITLECOLOR;
         cell.modle = _searchDataArray[indexPath.row];
    }else
    {
         cell.symbolLable.textColor = MAINTITLECOLOR1;
        if (indexPath.row ==0)
        {
            cell.symbolLable.text = Localized(@"search_History");
            cell.searchimageView.image = [UIImage imageNamed:@"deleteSearchData"];
        }else
        {
           
            cell.modle = _searchDataArray[indexPath.row -1];
        }
        
    }
   
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isSearch) {
        HomeModle *modle = self.searchDataArray[indexPath.row];
        
        Y_StockChartViewController * Y_StockChartVC = [[Y_StockChartViewController alloc] init];
        Y_StockChartVC.modle = modle;
         Y_StockChartVC.isleftPush = NO;
        [self.navigationController pushViewController:Y_StockChartVC animated:YES];
        /*! 保存历史数据 */
        if ([_searchVM readHistory].count==0) {
            [self reloadView:modle.name];
            
        }else{
            [self reloadView:modle.name];
        }
    }else
    {
        if (indexPath.row ==0) //清楚历史记录
        {
            [self deleteAll];
        }else
        {
            HomeModle *modle = self.searchDataArray[indexPath.row -1];
            Y_StockChartViewController * Y_StockChartVC = [[Y_StockChartViewController alloc] init];
            Y_StockChartVC.modle = modle;
             Y_StockChartVC.isleftPush = NO;
            [self.navigationController pushViewController:Y_StockChartVC animated:YES];
        }
       
    }
   
    
}
#pragma mark  ---- 垃圾桶按钮删除历史记录

- (void)deleteAll{
    WeakSelf
    CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"search_delete_History")
                                                                             titleStr:Localized(@"search_delete_History_mesaage")
                                                                              openUrl:@""
                                                                              confirm:Localized(@"transaction_OK")
                                                                               cancel:Localized(@"transaction_cancel")
                                                                                state:2
                                                                        RechargeBlock:^{
                                                                            
                                                                            [weakSelf deleteALLHistory];
                                                                            
                                                                        }];
    aleartVC.animationStyle = LXASAnimationTopShake;
    [aleartVC showLXAlertView];
}
- (void)deleteALLHistory
{
    WeakSelf
    [weakSelf.searchVM deleteHistory:@""];
    [weakSelf.searchDataArray removeAllObjects];
    [weakSelf.tableView reloadData];
    [self placeholderViewWithFrame:self.tableView.frame title:Localized(@"search_no_Historysymbol")];
}
#pragma mark --- SearchDelegate
/*! 新增历史搜索 */
- (void)searchWithStr:(NSString *)text{
    
    NSString *str = [text uppercaseString]; //把字符串中的字母转成大写
    [_searchDataArray removeAllObjects];
     NSArray * dataArray = [NSArray bg_arrayWithName:FMDBName_Symbol];
    for (HomeModle * modle in dataArray) {
        if ([modle.name containsString:str]) {
            
            [self.searchDataArray addObject:modle];
        }
    }
    _isSearch = YES;
    [self.tableView reloadData];
    [self placeholderViewWithFrame:self.tableView.frame title:Localized(@"search_no_symbol")];
}
- (void)placeholderViewWithFrame:(CGRect)frame title:(NSString *)title
{
    if (_searchDataArray.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:_tableView.frame NoNetwork:NO];
        _workView.titlelable.text = title;
        [_tableView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
    
}

- (void)reloadView:(NSString *)str{
    [_searchVM saveHistory:str];
}


- (void)searchWithcancel
{
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
